//
//  JRegisterController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/26.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JRegisterController.h"
#import <WXApi.h>
#define textFieldWidth  250
#define textFieldHeight  45


@interface JRegisterController ()

@property (nonatomic, strong) UITextField *nameTextField;
@property (nonatomic, strong) UITextField *pswTextField;
@property (nonatomic, strong) UITextField *codeTextField;
@property (nonatomic, strong) UITextField *repswTextField;
@property (nonatomic, strong) UIButton *codeBtn;
@property (nonatomic, assign) BOOL issel;
@property (nonatomic, copy) NSString *codeStr;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger timerNum;

@end

@implementation JRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    [super InitUI];

    if (_inputType == 0) { // 注册
        self.titleLabel.text = @"注册";
    }
    else if (_inputType == 1)
    {
        self.titleLabel.text = @"找回密码";
    }
    
    
    self.leftButton.hidden = NO;
    [self.leftButton setImage:[UIImage imageNamed:backBtnImg] forState:UIControlStateNormal];
    self.leftButton.frame = CGRectMake(8, self.leftButton.frame.origin.y, 30, 30);
    _issel = NO;
    _timerNum = 60;
    [self setConfigView];
    
}

- (void)setConfigView
{
    UITextField *nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(kWindowW/2.0 - textFieldWidth/2.0, 40, textFieldWidth - 88, textFieldHeight)];
    nameTextField.placeholder = @"请输入手机号";
    nameTextField.keyboardType = UIKeyboardTypeNumberPad;
    nameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    nameTextField.borderStyle = UITextBorderStyleRoundedRect;
    [self.contentView addSubview:nameTextField];
    _nameTextField = nameTextField;
    
    
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registBtn.frame = CGRectMake(nameTextField.right, nameTextField.top , 88, textFieldHeight);
    [registBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    registBtn.titleLabel.font = kFONT_TITLE(16);
    registBtn.backgroundColor = [UIColor redColor];
//    [registBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [registBtn addTarget:self action:@selector(registBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:registBtn];
    _codeBtn = registBtn;
    
    UITextField *pswTextField = [[UITextField alloc]initWithFrame:CGRectMake(nameTextField.left, nameTextField.bottom + 20, textFieldWidth, textFieldHeight)];
    pswTextField.placeholder = @"请输验证码";
    nameTextField.keyboardType = UIKeyboardTypeNumberPad;
    pswTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    pswTextField.borderStyle = UITextBorderStyleRoundedRect;
    [self.contentView addSubview:pswTextField];
    _codeTextField = pswTextField;
    
    UITextField *nameTextField1 = [[UITextField alloc]initWithFrame:CGRectMake(pswTextField.left, pswTextField.bottom + 20, textFieldWidth, textFieldHeight)];
    nameTextField1.placeholder = @"请输入密码";
    nameTextField1.secureTextEntry = YES;

    nameTextField1.keyboardType = UIKeyboardTypeASCIICapable;
    nameTextField1.clearButtonMode = UITextFieldViewModeWhileEditing;
    nameTextField1.borderStyle = UITextBorderStyleRoundedRect;
    [self.contentView addSubview:nameTextField1];
    _pswTextField = nameTextField1;
    
    UITextField *pswTextField2 = [[UITextField alloc]initWithFrame:CGRectMake(nameTextField1.left, nameTextField1.bottom + 20, textFieldWidth, textFieldHeight)];
    pswTextField2.placeholder = @"请再次输入密码";
    pswTextField2.secureTextEntry = YES;
    pswTextField2.keyboardType = UIKeyboardTypeASCIICapable;
    pswTextField2.clearButtonMode = UITextFieldViewModeWhileEditing;
    pswTextField2.borderStyle = UITextBorderStyleRoundedRect;
    [self.contentView addSubview:pswTextField2];
    _repswTextField = pswTextField2;
    
    UIButton *registBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    registBtn2.frame = CGRectMake(pswTextField2.left, pswTextField2.bottom + 20 , pswTextField2.width, 40);
    [registBtn2 setTitle:@"注册" forState:UIControlStateNormal];
    registBtn2.titleLabel.font = kFONT_TITLE(16);
    registBtn2.backgroundColor = [UIColor redColor];
    //    [registBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [registBtn2 addTarget:self action:@selector(registBtn2Click:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:registBtn2];
    
    
}

// 发送验证码
- (void)registBtnClick:(UIButton *)btn
{
    NSString *phone = _nameTextField.text;
    if (phone.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"手机号不能为空"];
        return;
    }
    
    if (![self validateBandCard:phone regularString:REG_PHONENUM_STR]) {
        [SVProgressHUD showErrorWithStatus:@"手机号格式不正确"];
        return;
    }

    if (_issel == NO) {
        _issel = YES;
        [self startTimer];
        
        NSString *sendCodeUrl = @"BusinessSettled/GetBusinessSettledCheckCode";
        [JNetManager sendCodeToTelURL:sendCodeUrl tel:phone success:^(id response) {
            if (response) {
                
                self.codeStr = [NSString stringWithString:response];
                [SVProgressHUD showSuccessWithStatus:@"发送验证码成功"];
            }
        } failure:^(NSString *err) {
            [SVProgressHUD showErrorWithStatus:err];
        }];
    }
}

// 注册
- (void)registBtn2Click:(UIButton *)btn
{
    NSString *phone = _nameTextField.text;
    NSString *psw = _pswTextField.text;
    NSString *rePsw = _repswTextField.text;
    NSString *code = _codeTextField.text;
    if (phone.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"手机号不能为空"];
        return;
    }
    
    if (psw.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"密码不能为空"];
        return;
    }
    
    if (rePsw.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"再次密码不能为空"];
        return;
    }
    
    
    if (![self validateBandCard:phone regularString:REG_PHONENUM_STR]) {
        [SVProgressHUD showErrorWithStatus:@"手机号格式不正确"];
        return;
    }
    
//    if (![self.codeStr isEqualToString:code]) {
//        [SVProgressHUD showErrorWithStatus:@"验证码输入不正确"];
//        return;
//    }
    
    if (![self validateBandCard:psw regularString:REG_PswNum_STR]) {
        [SVProgressHUD showErrorWithStatus:@"请输入6-18位密码"];
        return;
    }
    
    if (![psw isEqualToString:rePsw]) {
        [SVProgressHUD showErrorWithStatus:@"两次输入的密码不一致"];
        return;
    }
    
//    "Id"：1，
//    Code："",//验证码
//Tel:"",//电话
//Pwd:"",//密码
//    PwdTwo：""，//确认密码
    
    if (_inputType == 0) { // 注册
        NSDictionary *dic = @{@"Code":code,
                              @"Tel":phone,
                              @"Pwd":psw,
                              @"PwdTwo":rePsw,
                              @"Id":@([GLOBALDATA userInfoModel].CustomerId)};
        
        
        
        NSString *url = @"Customers/RegisteCustomer";
        [JNetManager registRequestURL:url parperDic:dic success:^(id response) {
            if ([response integerValue] == 1) {
                [SVProgressHUD showSuccessWithStatus:@"注册成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } failure:^(NSString *err) {
            [SVProgressHUD showErrorWithStatus:err];
        }];
    }
    else if (_inputType == 1)
    {
        NSLog(@"找回密码");
    }
    
    
}

- (void)sendCodeRequest {
    
}

- (void)timermethod {
    if (_timerNum > 0) {
        _timerNum -= 1;
        [_codeBtn setTitle:[NSString stringWithFormat:@"%ld秒后重试",_timerNum] forState:UIControlStateNormal];
        _codeBtn.backgroundColor = kRGBColor(220, 220, 220);
        _codeBtn.enabled = NO;
//        [self startTimer];
    }
    else
    {
        
        [self stopTimer];
    }
}

- (void)startTimer {
    if (_timer == nil) {
        _timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timermethod) userInfo:nil repeats:YES];
    }
//    [_timer fire];
    // 3.将定时器添加到事件循环
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)stopTimer {
    [_timer invalidate];
    _timer = nil;
    _timerNum = 60;
    _issel = NO;
    _codeBtn.enabled = YES;
    [_codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    _codeBtn.backgroundColor = [UIColor redColor];
}

- (void)leftButtonClick:(UIButton *)leftButton
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)validateBandCard:(NSString *)baneCard regularString:(NSString *)regularString
{
    BOOL flag;
    if (baneCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSPredicate *bandCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regularString];
    return [bandCardPredicate evaluateWithObject:baneCard];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
